class InvoiceDetailsController < ApplicationController
  before_action :set_invoice_detail, only: [:show, :edit, :update, :destroy]
  
  # GET /invoice_details
  # GET /invoice_details.json
  def index
    @invoice_details = InvoiceDetail.all
  end

  # GET /invoice_details/1
  # GET /invoice_details/1.json
  def show
  end

  # GET /invoice_details/new
  def new
    @invoice_detail = InvoiceDetail.new
    @stock_logging = @invoice_detail.build_stock_logging
  end

  # GET /invoice_details/1/edit
  def edit
  end

  # POST /invoice_details
  # POST /invoice_details.json
  def create
    @stock_logging = StockLogging.new(:drug_id => params[:invoice_detail][:stock_loggings][:drug_id], :stock_id  => params[:invoice_detail][:stock_loggings][:stock_id], :quantity  => params[:invoice_detail][:stock_loggings][:quantity], :inventory_id  => params[:invoice_detail][:stock_loggings][:inventory_id], :stock_logging_category_id  => params[:invoice_detail][:stock_loggings][:stock_logging_category_id])
    #comment, I am not really sure how to calling nested params here only for stock_logging attributes, thats way I put manually one by one. sorry 
    respond_to do |format|
    	if @stock_logging.valid?
			#find existing stock
			@stocks = Stock.find_by(drug_id: @stock_logging.drug_id, inventory_id: @stock_logging.inventory_id)
			@drug = Drug.find(@stock_logging.drug_id)
			#check in/out stocks (1 -> in, 2 -> out)
			if (@stock_logging.stock_logging_category_id == 1)
				if @stock_logging.save
					if (@stocks != nil)
						update_stock = @stocks.quantity + @stock_logging.quantity
						@stocks.update(:quantity => update_stock, :inventory_id => @stock_logging.inventory_id)
					else
						@stocks = @drug.stocks.create(:drug_id => @drug.id, :inventory_id => @stock_logging.inventory_id, :quantity => @stock_logging.quantity)	
					end
					@stock_logging.update(:stock_id => @stocks.id, :inventory_id => @stock_logging.inventory_id)
					#create the drug stock_logging links
					@drug.stock_loggings << @stock_logging
				else
					format.html { render :new }
				end
			else
				if (@stocks != nil)
					if (@stocks.quantity >= @stock_logging.quantity)
						if @stock_logging.save
							update_stock = @stocks.quantity - @stock_logging.quantity
							@stocks.update(:quantity => update_stock, :inventory_id => @stock_logging.inventory_id)
							@stock_logging.update(:stock_id => @stocks.id, :inventory_id => @stock_logging.inventory_id)
							#create the drug stock_logging links
							@drug.stock_loggings << @stock_logging
						else
							format.html { render :new }
						end
					else
						format.html { render :new }
					end
				else
					format.html { render :new }
				end
			end
		else
			format.html { render :new }
		end
	#end
    
    #@invoice_detail = InvoiceDetail.new(invoice_detail_params)
    @invoice = Invoice.find(params[:invoice_id])
	@invoice_detail = @invoice.invoice_details.create(invoice_detail_params)
	@stock_logging.invoice_detail = @invoice_detail
	#@stock_logging = @invoice_detail.create_stock_logging(:drug_id => 1, :stock_id => 1, :quantity => 100, :inventory_id => 1, :stock_logging_category_id => 1)
	#I used to try this code above to create stock_logging without re-write all the stock_logging code above. it works to create the record but doesn't run the function that I have created on the stock_logging_controller
	
	total = InvoiceDetail.where(:invoice_id => params[:invoice_id]).sum(:fee)
	discount = InvoiceDetail.where(:invoice_id => params[:invoice_id]).sum(:discount)
	@invoice.update(:total_fee => total, :total_discount => discount)
    #respond_to do |format|
      if @invoice_detail.save
        format.html { redirect_to @invoice, notice: 'Invoice detail was successfully created.' }
        format.json { render :show, status: :created, location: @invoice_detail }
      else
        format.html { render :new }
        format.json { render json: @invoice_detail.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /invoice_details/1
  # PATCH/PUT /invoice_details/1.json
  def update
  	#get previous value of stock_logging before be updated
  	@invoice_detail_selected = InvoiceDetail.find(params[:id])
	@prev_value = StockLogging.find(@invoice_detail_selected.stock_logging_id)
    respond_to do |format|
      if @stock_logging.update(:drug_id => params[:invoice_detail][:stock_loggings][:drug_id], :stock_id  => params[:invoice_detail][:stock_loggings][:stock_id], :quantity  => params[:invoice_detail][:stock_loggings][:quantity], :inventory_id  => params[:invoice_detail][:stock_loggings][:inventory_id], :stock_logging_category_id  => params[:invoice_detail][:stock_loggings][:stock_logging_category_id])
		
		#find existing stock
		@stocks_ori = Stock.find_by(drug_id: @prev_value.drug_id, inventory_id: @prev_value.inventory_id)
		#Redo the Stock quantity
		#check in/out stocks (1 -> in, 2 -> out)
		if (@prev_value.stock_logging_category_id == 1)
			redo_stock = @stocks_ori.quantity - @prev_value.quantity
		else
			redo_stock = @stocks_ori.quantity + @prev_value.quantity
		end
		@stocks_ori.update(:quantity => redo_stock, :inventory_id => @prev_value.inventory_id)
        
        #update stock with new the value
        #find existing stock
		@stocks = Stock.find_by(drug_id: @stock_logging.drug_id, inventory_id: @stock_logging.inventory_id)
		@drug = Drug.find(@stock_logging.drug_id)
		#check in/out stocks (1 -> in, 2 -> out)
		if (@stock_logging.stock_logging_category_id == 1)
			if @stock_logging.save
				if (@stocks != nil)
					update_stock = @stocks.quantity + @stock_logging.quantity
					@stocks.update(:quantity => update_stock, :inventory_id => @stock_logging.inventory_id)
				else
					@stocks = @drug.stocks.create(:drug_id => @drug.id, :inventory_id => @stock_logging.inventory_id, :quantity => @stock_logging.quantity)	
				end
				@stock_logging.update(:stock_id => @stocks.id, :inventory_id => @stock_logging.inventory_id)
				#create the drug stock_logging links when switch into another drug
				if (@prev_value.drug_id != @stock_logging.drug_id)
					@stock_logging.drugs = Drug.where(:id => @stock_logging.drug_id)
				end
			else
				format.html { render :edit }
			end
		else
			if (@stocks != nil)
				if (@stocks.quantity >= @stock_logging.quantity)
					if @stock_logging.save
						update_stock = @stocks.quantity - @stock_logging.quantity
						@stocks.update(:quantity => update_stock, :inventory_id => @stock_logging.inventory_id)
						@stock_logging.update(:stock_id => @stocks.id, :inventory_id => @stock_logging.inventory_id)
						#create the drug stock_logging links when switch into another drug
						if (@prev_value.drug_id != @stock_logging.drug_id)
							@stock_logging.drugs = Drug.where(:id => @stock_logging.drug_id)
						end
					else
						format.html { render :edit }
					end
				else
					format.html { render :edit }
				end
			else
				format.html { render :edit }
			end
		end
      else
        format.html { render :edit }
        format.json { render json: @stock_logging.errors, status: :unprocessable_entity }
      end
    
  	
  	@invoice = Invoice.find(params[:invoice_id])

      if @invoice_detail.update(invoice_detail_params)
      	total = InvoiceDetail.where(:invoice_id => params[:invoice_id]).sum(:fee)
		discount = InvoiceDetail.where(:invoice_id => params[:invoice_id]).sum(:discount)
		@invoice.update(:total_fee => total, :total_discount => discount)
        
        format.html { redirect_to @invoice, notice: 'Invoice detail was successfully updated.' }
        format.json { render :show, status: :ok, location: @invoice_detail }
      else
        format.html { render :edit }
        format.json { render json: @invoice_detail.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /invoice_details/1
  # DELETE /invoice_details/1.json
  def destroy
    #get previous value of stock_logging before be deleted
	@invoice_detail_selected = InvoiceDetail.find(params[:id])
	@prev_value = StockLogging.find(@invoice_detail_selected.stock_logging_id)
	@drug = Drug.find(@prev_value.drug_id)
    respond_to do |format|
		
		
		#find existing stock
		@stocks_ori = Stock.find_by(drug_id: @prev_value.drug_id, inventory_id: @prev_value.inventory_id)
		#Redo the Stock quantity
		#check in/out stocks (1 -> in, 2 -> out)
		if (@prev_value.stock_logging_category_id == 1)
			redo_stock = @stocks_ori.quantity - @prev_value.quantity
		else
			redo_stock = @stocks_ori.quantity + @prev_value.quantity
		end
		@stocks_ori.update(:quantity => redo_stock, :inventory_id => @prev_value.inventory_id)
	
        @invoice = Invoice.find(params[:invoice_id])
    	@prev_value.destroy
		#@invoice_detail.destroy
		total = InvoiceDetail.where(:invoice_id => params[:invoice_id]).sum(:fee)
		discount = InvoiceDetail.where(:invoice_id => params[:invoice_id]).sum(:discount)
		@invoice.update(:total_fee => total, :total_discount => discount)

		  format.html { redirect_to @invoice, notice: 'Invoice detail was successfully destroyed.' }
      	  format.json { head :no_content }
    	end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_invoice_detail
      @invoice_detail = InvoiceDetail.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def invoice_detail_params
      params.require(:invoice_detail).permit(:invoice_id, :invoice_item_type_id, :fee, :discount, :created_at, :updated_at, :created_by, :updated_by, :stock_logging_id, 
      #invoice_item_type_attributes: [:label],
      stock_logging_attributes: [:drug_id, :stock_id, :quantity, :inventory_id, :stock_logging_category_id, :created_at, :updated_at, :created_by, :updated_by],
      #:invoice_item_type_id => []
      )
    end
end
